package cn.ldw.handler;

import cn.ldw.pojo.User;
import cn.ldw.utils.ErrorInfo;
import cn.ldw.utils.JwtTokenUtils;
import cn.ldw.utils.UserThreadLocal;
import cn.ldw.vo.Result;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Component
public class LoginHandler implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if(StringUtils.isBlank(token)) {
            Result result = Result.fail(ErrorInfo.TOKEN_EXPRIE.getCode(), ErrorInfo.TOKEN_EXPRIE.getMessage());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        Map<String, Object> map = JwtTokenUtils.checkToken(token);
        if(map == null) {
            Result result = Result.fail(ErrorInfo.TOKEN_ERROR.getCode(), ErrorInfo.TOKEN_ERROR.getMessage());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        String userJson = redisTemplate.opsForValue().get("token_" + token);
        if(StringUtils.isBlank(userJson)) {
            Result result = Result.fail(ErrorInfo.TOKEN_EXPRIE.getCode(), ErrorInfo.TOKEN_EXPRIE.getMessage());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        User user = JSON.parseObject(userJson, User.class);
        UserThreadLocal.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
